#!/bin/env python
#-*- coding:utf-8 -*-
import urllib2,urllib,httplib,urlparse,sys
import re
from urllib import urlopen

def divide2pic(html_data):
    pattern = re.compile(r'<img.*?src=".*?\.jpg".*?>')
    match = pattern.findall(html_data)
    if match:
        for line in match:
            print line
            t_data = line.strip().split("src=\"")[1].strip().split("\"")[0]
            pic_list.append(t_data)
    return pic_list

def is404(html_data):
    if (html_data.find("很抱歉，你访问的贴子不存在。")!=-1):
        return True
    else:
        return False

def reporthook(blocks_read, block_size, total_size): 
    if not blocks_read: 
        print ('Connection opened') 
    if total_size < 0: 
        print ('Read %d blocks' % blocks_read) 
    else:
        print('downloading:%d KB, totalsize:%d KB' % (blocks_read*block_size/1024.0,total_size/1024.0))

def downpic():
    for pic in pic_list:
        try:
            urllib.urlretrieve(pic , pic.strip().split("/")[-1] , reporthook)
        except:
            print "download ERROR";x
if __name__=='__main__':
    url = "http://tieba.baidu.com/p/1585565828?"
    global  pic_list
    pic_list = []
    params = { "pn":1}
    while 1:
        if (params["pn"] > 10):
            break;
        t_url = url + urllib.urlencode(params)
        print t_url
        response = urllib.urlopen(t_url)
        html_data = response.read()
        if(is404(html_data)):
            break;
        print divide2pic(html_data)
        params["pn"]+=1
    downpic()
